import React, { useState, useEffect } from 'react'
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Popconfirm,
} from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getRoutes, createRoute, updateRoute, deleteRoute } from '../api/gateway'

export default function RoutesManagement() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editingRoute, setEditingRoute] = useState<any>(null)
  const [form] = Form.useForm()
  const queryClient = useQueryClient()

  const { data: routes, isLoading } = useQuery({
    queryKey: ['routes'],
    queryFn: getRoutes,
    retry: false,
  })

  const createMutation = useMutation({
    mutationFn: createRoute,
    onSuccess: () => {
      message.success('创建成功')
      setIsModalOpen(false)
      form.resetFields()
      queryClient.invalidateQueries({ queryKey: ['routes'] })
    },
    onError: () => {
      message.error('创建失败')
    },
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => updateRoute(id, data),
    onSuccess: () => {
      message.success('更新成功')
      setIsModalOpen(false)
      setEditingRoute(null)
      form.resetFields()
      queryClient.invalidateQueries({ queryKey: ['routes'] })
    },
    onError: () => {
      message.error('更新失败')
    },
  })

  const deleteMutation = useMutation({
    mutationFn: deleteRoute,
    onSuccess: () => {
      message.success('删除成功')
      queryClient.invalidateQueries({ queryKey: ['routes'] })
    },
    onError: () => {
      message.error('删除失败')
    },
  })

  const handleAdd = () => {
    setEditingRoute(null)
    setIsModalOpen(true)
  }

  const handleEdit = (record: any) => {
    setEditingRoute(record)
    form.setFieldsValue(record)
    setIsModalOpen(true)
  }

  const handleDelete = (id: string) => {
    deleteMutation.mutate(id)
  }

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      if (editingRoute) {
        updateMutation.mutate({ id: editingRoute.id, data: values })
      } else {
        createMutation.mutate(values)
      }
    } catch (error) {
      console.error('Validation failed:', error)
    }
  }

  // 处理创建和更新后的响应
  useEffect(() => {
    if (createMutation.isSuccess && createMutation.data) {
      const newRoute = createMutation.data.route || createMutation.data
      if (newRoute && newRoute.id) {
        queryClient.invalidateQueries({ queryKey: ['routes'] })
      }
    }
  }, [createMutation.isSuccess, createMutation.data, queryClient])

  useEffect(() => {
    if (updateMutation.isSuccess) {
      queryClient.invalidateQueries({ queryKey: ['routes'] })
    }
  }, [updateMutation.isSuccess, queryClient])

  const columns = [
    {
      title: '路由名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '目标地址',
      dataIndex: 'target',
      key: 'target',
    },
    {
      title: '方法',
      dataIndex: 'methods',
      key: 'methods',
      render: (methods: string[]) => (methods && Array.isArray(methods) ? methods.join(', ') : '-'),
    },
    {
      title: '需要认证',
      dataIndex: 'auth_required',
      key: 'auth_required',
      render: (auth: boolean) => (auth ? '是' : '否'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个路由吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between' }}>
        <h1 style={{ margin: 0 }}>路由管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增路由
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={routes || []}
        loading={isLoading}
        rowKey="id"
      />
      <Modal
        title={editingRoute ? '编辑路由' : '新增路由'}
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={() => {
          setIsModalOpen(false)
          setEditingRoute(null)
          form.resetFields()
        }}
        confirmLoading={createMutation.isLoading || updateMutation.isLoading}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="路由名称"
            rules={[{ required: true, message: '请输入路由名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径' }]}
          >
            <Input placeholder="/api/v1/users/**" />
          </Form.Item>
          <Form.Item
            name="target"
            label="目标地址"
            rules={[{ required: true, message: '请输入目标地址' }]}
          >
            <Input placeholder="http://localhost:8001" />
          </Form.Item>
          <Form.Item
            name="methods"
            label="HTTP 方法"
            rules={[{ required: true, message: '请选择方法' }]}
          >
            <Select mode="multiple" placeholder="选择 HTTP 方法">
              <Select.Option value="GET">GET</Select.Option>
              <Select.Option value="POST">POST</Select.Option>
              <Select.Option value="PUT">PUT</Select.Option>
              <Select.Option value="DELETE">DELETE</Select.Option>
              <Select.Option value="PATCH">PATCH</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="auth_required" valuePropName="checked">
            <Switch checkedChildren="需要认证" unCheckedChildren="无需认证" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

